/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.CommonUtil;
import Common.Global;
import DAO.AccountDAO;
import DAO.CollectionDAO;
import DAO.FeedbackDAO;
import DAO.MessageDAO;
import DAO.NotificationDAO;
import DAO.PriceHistoryDAO;
import DAO.TrackedProductDAO;
import hibernate.entity.Account;
import hibernate.entity.Feedback;
import hibernate.entity.TrackedProduct;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author USERT
 */
public class AdminController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        try {
            String action = request.getParameter("btAction");
            if (action.equals("LoadPage")) {
                AccountDAO accDao = new AccountDAO();
                TrackedProductDAO TPDao = new TrackedProductDAO();
                FeedbackDAO feedbackDao = new FeedbackDAO();

                List<Account> dbAccount = CommonUtil.getLastTenItem(accDao.getAllAccount());
                List<TrackedProduct> dbTrackedProduct = CommonUtil.getLastTenItem(TPDao.getAllProductForUpdatePrice());
                session.setAttribute("DBACCOUNT", dbAccount);
                session.setAttribute("DBTRACKEDPRODUCT", dbTrackedProduct);
                session.setAttribute("RADIO", CommonUtil.readProperties("radio"));
                session.setAttribute("ACCCOUNT", accDao.countAccount());
                session.setAttribute("TPCOUNT", TPDao.countTrackedProduct());
                session.setAttribute("FBCOUNT", feedbackDao.countFeedback());
                session.setAttribute("TIMEINTERVAL", (Global.timeInterval));
                response.sendRedirect(Global.Adminpage);
            } else if (action.equals("searchAccount")) {
                session.removeAttribute("ACCOUNTS");
                String txtSearch = request.getParameter("txtSearch");
                AccountDAO accDAO = new AccountDAO();
                List<Account> result = accDAO.searchAccount(txtSearch);
                session.setAttribute("SEARCHACCOUNT", result);
                response.sendRedirect(Global.AUsernpage);
            } else if (action.equals("loadProduct")) {
                TrackedProductDAO TPDao = new TrackedProductDAO();
                session.removeAttribute("SEARCHTRACKEDPRODUCTS");
                session.setAttribute("TRACKEDPRODUCTS", TPDao.getAllProductForUpdatePrice());
                response.sendRedirect(Global.AProductpage);
            } else if (action.equals("searchProduct")) {
                session.removeAttribute("TRACKEDPRODUCTS");
                String txtSearchProduct = request.getParameter("txtSearch");
                TrackedProductDAO tdProductDAO = new TrackedProductDAO();
                List<TrackedProduct> result = tdProductDAO.searchProductLikeName(txtSearchProduct);
                session.setAttribute("SEARCHTRACKEDPRODUCTS", result);
                response.sendRedirect(Global.AProductpage);
            } else if (action.equals("loadUser")) {
                session.removeAttribute("SEARCHACCOUNT");
                AccountDAO AccDao = new AccountDAO();
                session.setAttribute("ACCOUNTS", AccDao.getAllAccount());
                response.sendRedirect(Global.AUsernpage);
            } else if (action.equals("showAccountDetail")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    int accountID = Integer.parseInt(request.getParameter("accountDetailID"));
                    AccountDAO accDAO = new AccountDAO();
                    Account account = accDAO.getAccountById(accountID);
                    session.setAttribute("SHOWACCOUNTDETAIL", account);
                    response.sendRedirect(Global.AUsernpage);
                } else {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("updateActive")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    int accountID = Integer.parseInt(request.getParameter("updateActiveID"));
                    AccountDAO accDAO = new AccountDAO();
                    Account account = accDAO.getAccountById(accountID);
                    boolean active = account.isActive();
                    String url = "AdminController?btAction=loadUser";
                    if (active == true) {
                        boolean updateActive = false;
                        accDAO.updateActive(updateActive, accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    } else {
                        boolean updateActive = true;
                        accDAO.updateActive(updateActive, accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                } else {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("changeRole")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    int accountID = Integer.parseInt(request.getParameter("changeRoleID"));
                    AccountDAO accDAO = new AccountDAO();
                    Account account = accDAO.getAccountById(accountID);
                    int roleID = account.getRole().getRoleID();
                    String url = "AdminController?btAction=loadUser";
                    if (roleID == 3) {
                        int changeRoleID = 2;
                        accDAO.updateRole(changeRoleID, accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    } else if (roleID == 2) {
                        int changeRoleID = 3;
                        accDAO.updateRole(changeRoleID, accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                } else {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("deleteAccount")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    int accountID = Integer.parseInt(request.getParameter("deleteAccountID"));
                    FeedbackDAO fbDAO = new FeedbackDAO();
                    fbDAO.deleteFeedbackbyAccountID(accountID);
                    MessageDAO msDAO = new MessageDAO();
                    msDAO.deleteReceivedMessagebyAccountID(accountID);
                    msDAO.deleteSentMessagebyAccountID(accountID);
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    AccountDAO accDAO = new AccountDAO();
                    NotificationDAO noDAO = new NotificationDAO();
                    noDAO.deleteNotificationbyAccountID(accountID);
                    PriceHistoryDAO phDAO = new PriceHistoryDAO();
                    List<TrackedProduct> trackedProducts = tpDAO.getTrackedProductbyAccount_Id(accountID);
                    String url = "AdminController?btAction=loadUser";
                    if (trackedProducts != null) {
                        List<Integer> flag = new ArrayList<Integer>();
                        for (int i = 0; i < trackedProducts.size(); i++) {
                            Integer a = trackedProducts.get(i).getTrackedProductId();
                            flag.add(a);
                        }
                        for (int i = 0; i < flag.size(); i++) {
                            int id = flag.get(i);
                            phDAO.deletePricebyProductID(id);
                        }
                        tpDAO.deleteTrackedProductbyAccountID(accountID);
                        CollectionDAO colDAO = new CollectionDAO();
                        colDAO.deleteCollectionbyAccountID(accountID);
                        accDAO.delete(accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    } else if (trackedProducts == null) {
                        CollectionDAO colDAO = new CollectionDAO();
                        colDAO.deleteCollectionbyAccountID(accountID);
                        accDAO.delete(accountID);
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                } else {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("Update time")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {

                    double newtime = request.getParameter("newTimeInterval").equals("") ? 1 :
                        Double.parseDouble(request.getParameter("newTimeInterval"));
                    int time = (int) (newtime);
                    Global.timeInterval = time;
                    session.setAttribute("TIMEINTERVAL", Global.timeInterval);
                    //CANCLE TIMER
                    Global.timer.cancel();
                    //CREATE NEW TIMER & USER NEW TIME INTERVAL
                    Global.timer = new Timer();
                    Global.timer.scheduleAtFixedRate(new TimerTask() {

                        public void run() {
                            CommonUtil.updateInfo();
                        }//End of Run
                    }, 1000, Global.timeInterval * 1000);
                    //WRITE NEW VALUE TO PROPERTIES FILE
                    boolean result = CommonUtil.writeProperty(Global.timeInterval.toString(), Global.timePropName, Global.propPath);


                    response.sendRedirect(Global.AIntervalTime + "?result=" + result);
                } else {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.trim().equals("Save")) {
                String radio = request.getParameter("radiobutton");
                String newradio = radio.equals("auto") ? "auto" : "manual";
                if (newradio.equals("manual")) {
                    Global.timer.cancel();
                } else {
                    Global.timer = new Timer();
                    Global.timer.scheduleAtFixedRate(new TimerTask() {

                        public void run() {
                            CommonUtil.updateInfo();
                        }//End of Run
                    }, 1000, Global.timeInterval * 1000);
                }
                session.setAttribute("RADIO", newradio);
                CommonUtil.writeProperty(newradio, "radio", Global.propPath);
                response.sendRedirect(Global.intervalPage);

            } else if (action.equals("Run update")) {
                Global.timer = new Timer();

                Global.timer.scheduleAtFixedRate(new TimerTask() {

                    public void run() {
                        CommonUtil.updateInfo();

                    }//End of Run
                }, 1000, 1000000000);

                response.sendRedirect(Global.intervalPage);


            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
